<?php
declare (strict_types=1);

namespace app\service;

use app\model\TCategory;
use app\model\TSubCategory;
use app\traits\ServiceTrait;
use app\util\JwtUtil;
use app\service\AuthGroupService;
use think\facade\Db;

/**
 * 分类
 * Class TCategoryService
 * @package app\service
 */
class TCategoryService
{
    use ServiceTrait;

    /**
     * @param $field
     * @return array
     */
    public static function getLists($labelId = 0, $page = 1, $psize = 20, $field = [])
    {
        $cates = config('goods.labelsCate');
        $labelIds = array_keys($cates);
        // 列表
        $table_cat = TCategory::$_table;
        $table_cat_sub = TSubCategory::$_table;
        if (in_array($labelId, $labelIds)) {
            // 如果存在
            $cids = $cates[$labelId]['cids'];
            $catList = Db::table($table_cat)->alias('c')->where([['id', 'in', $cids]])->field('c.id id, c.name, c.cat_name catName , c.remark')->select();
        } else {
            $catList = Db::table($table_cat)->alias('c')->field('c.id id, c.name, c.cat_name catName , c.remark')->select();
        }

        $data = [];
        foreach ($catList as $k => $v) {
            $subCateList = Db::table($table_cat_sub)->alias('sc')->where(['category_id' => $v['id']])->field('sc.id id, sc.cat_leaf_name as catLeafName, sc. category_id as categoryId, sc.name as name, sc.remark remark')->select();
            $subCategoryList = [];
            if (!empty($subCateList)) {
                $subCategoryList = $subCateList->toArray();
                foreach ($subCategoryList as &$sv) {
                    $sv['categoryName'] = $v['name'];
                }
            }
            $data[$k]['catName'] = $v['catName'];
            $data[$k]['id'] = $v['id'];
            $data[$k]['name'] = $v['name'];
            $data[$k]['remark'] = $v['remark'];
            $data[$k]['subCategoryList'] = $subCategoryList;
        }
        return $data;
    }
}
